import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get_core/get_core.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

import 'package:zz_listen_english/common/index.dart';

import '../../common/api/user/user.dart';
import '../../common/models/user/login_token.dart';
import '../../common/services/user.dart';


class LoginController extends GetxController {
  LoginController();
  GlobalKey fromKeyId = GlobalKey<FormState>();
  TextEditingController userNameController = TextEditingController(text: "zongzi");
  TextEditingController passwordController =
      TextEditingController(text: "123456");

  bool isShowIpSetting = false;

  _initData() {
    update(["login"]);
  }

  void onSignIn() async {
    String userName = userNameController.text;
    String password = passwordController.text;
    if (Constants.appIpAccount == userName &&
        password == Constants.appIpPassword) {
      isShowIpSetting = true;
      userNameController.text = "";
      passwordController.text = "";
      update(["login"]);
      return;
    }

    if ((fromKeyId.currentState as FormState).validate()) {
      Map<String, dynamic> res = await UserApi.login({"userName":userName,"password":password});
      if (res['code'] == "00000") {    
    // 本地保存 token
        LoginToken loginToken = LoginToken.fromJson(res["data"]);
         await UserService.to.setToken(loginToken.token!);
         await UserService.to.setLoginFlag(true);
         await UserService.to.getUserInfo();
      } else {
        EasyLoading.showError("账号或者密码错误！");
      }
    }
  }

  void onSetIp() {
     Get.toNamed(RouteNames.httpIpSet);
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

//获取全部app 的系统配置，并保存到缓存Storage


  @override
  void onClose() {
    super.onClose();
    userNameController.dispose();
    passwordController.dispose();
  }
}
